import detail from '../../lib/data/recdata.js';
import amounts from '../../lib/data/buycardata.js';
var WxParse = require('../../lib/wxParse/wxParse.js');
const util = require('../../utils/util.js');
const api = require('../../config/api.js');
const user = require('../../utils/user.js');
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    images: [],

    detail,
    modNum: '',
    num: 1,
    current: 1,
    hide: true,
    serHide: true,
    amounts,
    image: '/images/shops/s12.png',
    model: '',
    curIndex: 0,
    showtj: true,
    carNum: 0,
    lists: [],
    goodsDesc: "",

    id: '',
    primaryPicUrl: '',
    PicUrllist: [],

  },

  //获取商品详情信息
  getGoodInfo: function () {
    var that = this
    var ID = that.data.id;

    util.requestNoToken(api.GoodsInfo + ID, {}, "GET").then(function (res) {
      if (res.success) {
        wx.showLoading({
          title: '加载中',
        })
        if (res.success) {
          that.setData({
            id: res.obj.id,
            primaryPicUrl: res.obj.primaryPicUrl,
            listPicUrl: res.obj.listPicUrl,
            goodsName: res.obj.goodsName,
            accountIndex: res.obj.categoryId,
            marketPrice: res.obj.marketPrice,
            goodsBrief: res.obj.goodsBrief,
            goodsDesc: res.obj.goodsDesc,
            goodsSn: res.obj.goodsSn,
            keywords: res.obj.keywords,
            goodsUnit: res.obj.goodsUnit,
            categoryId: res.obj.categoryId,
            categoryName: res.obj.categoryName,
            retailPrice: res.obj.retailPrice,
            goodsNumber: res.obj.goodsNumber,
            createUserDeptId: res.obj.createUserDeptId,
            isHot: res.obj.isHot,
            isShare: res.obj.isShare
          });

          if (res.obj.deptName == null){
            that.setData({
              deptName: '官方自营'             
            })
          }else{
            that.setData({
              deptName: res.obj.deptName
            })
          }

          that.setData({
            model: '已选择：' + that.data.num + that.data.goodsUnit,
          })

          var goodsD = that.data.goodsDesc;
          WxParse.wxParse('goodsD', 'html', goodsD, that, 5);

          var listurl = that.data.listPicUrl.split(";");
          console.log(listurl);
          var img = that.data.images;

          for (var i = 0; i < listurl.length; i++) {
            img[i] = listurl[i];
          }

          that.setData({
            images: img
          })

          wx.hideLoading();
        }
      } else {
        wx.hideLoading();
        console.log("获取全部商品信息失败")
      }
    }).catch(function (res) {
      wx.hideLoading();
      console.log("获取数据失败！")
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.setNavigationBarTitle({
      title: '商品详情',
    })

    var that = this;

    that.setData({
      id: options.id,
    });

    that.getGoodInfo()

  },

  // 获取当前购物车数量的函数
  getCarNum: function (e) {
    var that = this
    let num = 0;
    let lis = wx.getStorageSync("lists");
    for (var i = 0; i < lis.length; i++) {
      num++
    }
    wx.setStorage({
      key: 'carNum',
      data: num
    })
    that.onShow();
    console.log("更新购物车")
  },

  //直接购买前做登录验证
  goBuycheck: function () {
    if (app.globalData.hasLogin) {
      this.goBuy()
    } else {
      wx.navigateTo({
        url: "/pages/auth/login/login"
      });
    }
  },

  //直接购买商品，不加入购物车
  goBuy: function (e) {
    let num = this.data.num;
    let hide = true;

    if (this.data.hide) {
      hide = false,
        this.setData({
          hide: false
        })
    }
    let temp = {
      id: this.data.id,
      title: this.data.goodsName,
      price: this.data.marketPrice,
      model: this.data.model,
      num: this.data.num,
      image: '',
      primaryPicUrl: this.data.primaryPicUrl,
      selected: false,
      hasCarNum: this.data.carNum,
      isTouchMove: false,
      createUserDeptId: this.createUserDeptId,
      categoryId: this.data.categoryId,
      categoryName: this.data.categoryName,
      marketPrice: this.data.marketPrice,
      retailPrice: this.data.retailPrice,
      goodsId: this.data.id,
      goodsName: this.data.goodsName,
      goodsNo: this.data.goodsSn,
      goodsNum: 0,
      goodsSales: 0,
      isShare: this.data.isShare
    }
    if (this.data.model) {
      var lists = [temp]
      var retailPrice = temp.retailPrice
      var totalPrice = (retailPrice * num).toFixed(2)
      var totalNum = temp.num
      var ordlists = {
        lists,
        totalPrice,
        totalNum
      }
      wx.setStorageSync("ordlists", ordlists)
    }
    console.log(this.data.lists)
    if (hide) {
      if (this.data.model) {
        wx.navigateTo({
          url: '/pages/checkout/checkout',
        })
      } else {
        wx.showToast({
          title: '购买商品数量不能为0',
          icon: 'none'
        })
      }
    }

  },

  //跳转购物车页面
  goCar(e) {
    var that = this
    wx.switchTab({
      url: "/pages/buycar/buycar",
      success: (res) => {
        wx.setStorage({
          key: 'carNum',
          data: that.data.carNum
        })
      }
    })
  },

  //添加物品至购物车登录验证
  addcarcheck: function () {
    if (app.globalData.hasLogin) {
      this.addCar()
    } else {
      wx.navigateTo({
        url: "/pages/auth/login/login"
      });
    }
  },

  //添加物品至购物车
  addCar: function (e) {
    var that = this
    let num = that.data.num;
    let carNum = that.data.carNum;
    let hide = true;

    if (that.data.hide) {
      hide = false,
        that.setData({
          hide: false
        })

    } else {

      let temp = {
        id: that.data.id,
        title: that.data.goodsName,
        price: that.data.marketPrice,
        model: that.data.model,
        num: that.data.num,
        image: '',
        primaryPicUrl: that.data.primaryPicUrl,
        selected: false,
        hasCarNum: that.data.carNum,
        isTouchMove: false,
        createUserDeptId: that.data.createUserDeptId,
        categoryId: that.data.categoryId,
        categoryName: that.data.categoryName,
        marketPrice: that.data.marketPrice,
        retailPrice: that.data.retailPrice,
        goodsId: that.data.id,
        goodsName: that.data.goodsName,
        goodsNo: that.data.goodsSn,
        goodsNumber: that.data.goodsNumber,
        goodsSales: that.data.goodsSales,
        deptName: that.data.deptName,
        isShare: this.data.isShare
      }
      if (that.data.model) {
        var lis = that.data.lists
        var k = 0;
        if (lis.length == 0) {
          var x = []
          x = x.concat(temp)
          that.setData({
            lists: x
          })
        } else {
          for (var i = 0; i < lis.length; i++) {
            if (lis[i].id == temp.id) {
              lis[i].model = temp.model
              lis[i].num += temp.num
              k++
            }
          }
          if (k !== 0) {
            that.setData({
              lists: lis
            })
          } else {
            var l = []
            l = l.concat(temp)
            l = l.concat(lis)
            that.setData({
              lists: l
            })
          }

        }

        wx.setStorageSync('lists', that.data.lists)
        wx.showToast({
          title: '加入购物车成功',
          icon: 'none'
        })
        that.getCarNum()
        that.setData({
          carNum: wx.getStorageSync("carNum")
        })



      } else {
        wx.showToast({
          title: '购买商品数量不能为0',
          icon: 'none'
        })
      }

      that.onShow()
    }
  },

  //查看同类型商品
  // switchCategory(e) {
  //   console.log(e)
  //   let index = e.currentTarget.dataset.index;
  //   if (index == 0) {
  //     this.setData({
  //       showtj: true
  //     })
  //   } else {
  //     this.setData({
  //       showtj: false
  //     })
  //   }
  //   this.setData({
  //     curIndex: e.currentTarget.dataset.index ? e.currentTarget.dataset.index : 0,
  //   })
  // },

  //选择商品规格
  // bindAmountChange(e) {
  //   let amounts = this.data.amounts;
  //   let strVal = e.detail.value;
  //   let image;
  //   for (let amount of amounts) {
  //     amount.checked = amount.value == strVal;
  //     if (amount.checked == true) {
  //       image = amount.image;
  //     }
  //   }
  //   this.setData({
  //     amounts,
  //     model: '已选择：' + strVal,
  //     image
  //   })
  // },


  //商品图片轮播
  changeSwiper(e) {
    var current = e.detail.current + 1;
    this.setData({
      current
    })
  },

  //显示底部菜单的状态
  actionSheet(e) {
    this.setData({
      hide: false,
    })
  },

  //隐藏底部菜单
  upactionSheet(e) {
    if (this.data.model) {
      this.data.modNum = '*' + this.data.num;
    }
    this.setData({
      hide: true,
      modNum: this.data.modNum,
      model: this.data.model
    })
  },

  //打开服务菜单
  // actionSer(e) {
  //   this.setData({
  //     serHide: false
  //   })
  // },

  //隐藏服务菜单
  // upactionSer(e) {
  //   this.setData({
  //     serHide: true
  //   })
  // },

  //对商品数量进行减操作
  dropNum(e) {
    var that = this;
    let num = that.data.num;
    let model = that.data.model;
    let modNum = that.data.modNum;
    num--;
    if (num <= 1) {
      wx.showToast({
        title: '数量至少为1',
        icon: 'none'
      })
      num = 1;
    }
    if (num >= 1) {
      that.setData({
        model: '已选择：' + num + that.data.goodsUnit,
        num,
      })
    }
  },

  //对商品数量进行加操作
  addNum(e) {
    var that = this;
    let num = that.data.num;
    let modNum = that.data.modNum;
    let model = that.data.model;
    if (num < that.data.goodsNumber) {
      num++;
      that.setData({
        model: '已选择：' + num + that.data.goodsUnit,
        num,
      })
    } else {
      wx.showToast({
        title: '已达到最大剩余库存量',
        icon: 'none'
      })
    }
  },

  //手动输入商品数量
  numchange: function (e) {
    var that = this;
    var x = JSON.parse(e.detail.value)
    if (x > that.data.goodsNumber) {
      wx.showToast({
        title: '购买数量不能大于库存数量',
        icon: 'none'
      })
      that.setData({
        num: that.data.goodsNumber,
      })
    } else if (x <= 0) {
      wx.showToast({
        title: '请至少购买一件商品',
        icon: 'none'
      })
      that.setData({
        num: 1,
      })
    } else {
      that.setData({
        num: x,
      })
    }
    that.setData({
      model: '已选择：' + that.data.num + that.data.goodsUnit,
    })
  },



  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that = this
    if (app.globalData.hasLogin) {

      wx.getStorage({
        key: 'carNum',
        success: (res) => {
          that.setData({
            carNum: res.data
          })
          app.globalData.carNum = that.data.carNum;
        }
      })
      wx.getStorage({
        key: 'lists',
        success: (res) => {
          that.setData({
            lists: res.data
          })
        },
      })
      util.buycarBar()
    }
  },



  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})